package com.example.sens.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.example.sens.entity.*;
import com.example.sens.mapper.*;
import com.example.sens.service.QuizService;
import com.example.sens.utils.Response;
import com.example.sens.utils.UUIDUtil;
import com.example.sens.vo.QuizAnswerVo;
import com.example.sens.vo.QuizQuestionVo;
import com.example.sens.vo.QuizVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <pre>
 *     用户业务逻辑实现类
 * </pre>
 *
 */
@Service
@Slf4j
public class QuizServiceImpl implements QuizService {

    @Autowired(required = false)
    private QuizMapper quizMapper;

    @Autowired(required = false)
    private QuizQuestionMapper quizQuestionMapper;
    @Autowired(required = false)
    private QuizAnswerMapper quizAnswerMapper;
    @Autowired(required = false)
    private UserQuizResultMapper userQuizResultMapper;
    @Autowired(required = false)
    private UserQuizMapper userQuizMapper;
    @Resource
    private ConclusionMapper conclusionMapper;
    @Resource
    private PerformanceMapper performanceMapper;

    @Override
    public Page<Quiz> findAll(Page<Quiz> page) {
        return page.setRecords(quizMapper.getByPage(page));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveQuiz(QuizVo quizVo) throws Exception{
        log.info("saveQuiz request==={}" + JSON.toJSONString(quizVo));
        if(quizVo == null || CollectionUtils.isEmpty(quizVo.getQuestionVoList())) {
            throw new Exception("传入参数有误");
        }
        Integer insertResult = null;
        // 先保存实验
        Quiz quiz = new Quiz();
        BeanUtils.copyProperties(quizVo,quiz);
        insertResult = quizMapper.insertQuiz(quiz);
        if(insertResult == null || insertResult != 1) {
            throw new Exception("保存实验失败");
        }
        if(quiz.getId() == null) {
            System.out.println("error======");
            throw new Exception("失败");
        }
        // 保存题目
        if(!CollectionUtils.isEmpty(quizVo.getQuestionVoList())) {
            for(QuizQuestionVo quizQuestionVo : quizVo.getQuestionVoList()) {
                quizQuestionVo.setQuizId(quiz.getId());
                QuizQuestion quizQuestion = new QuizQuestion();
                BeanUtils.copyProperties(quizQuestionVo,quizQuestion);
                if(quizQuestionMapper.insert(quizQuestion) != 1) {
                    throw new Exception("保存题目失败");
                }
                List<QuizAnswer> quizAnswers = new ArrayList<>();
                if(!CollectionUtils.isEmpty(quizQuestionVo.getQuizAnswerList())) {
                    quizAnswers.addAll(quizQuestionVo.getQuizAnswerList());
                    quizAnswers.forEach(v -> {
                        v.setQuestionId(quizQuestion.getId());
                    });
                }
                if(CollectionUtils.isEmpty(quizAnswers)) {
                    throw new Exception("选项为空");
                }
                insertResult = quizAnswerMapper.insertByList(quizAnswers);
                if(insertResult == null || insertResult != quizAnswers.size()) {
                    throw new Exception("保存选项错误");
                }
            }
        }
        // 保存题目答案
    }

    @Override
    public QuizVo getQuestionList(Long quizId) throws Exception {
        log.info("getQuestionList request" + quizId);
        QuizVo quizVo = new QuizVo();
        List<QuizQuestionVo> questionVoList = new ArrayList<>();
        quizVo.setQuestionVoList(questionVoList);
        // 获取所有选项
        List<QuizAnswerVo> answerList = quizAnswerMapper.getQuestionList(quizId);
        if(!CollectionUtils.isEmpty(answerList)) {
            // 根据题目把选项分组
            Map<Long,List<QuizAnswerVo>> map = answerList.stream().collect(Collectors.groupingBy(QuizAnswer::getQuestionId));
            for(Map.Entry<Long,List<QuizAnswerVo>> entry : map.entrySet()){
                QuizQuestionVo quizQuestionVo = new QuizQuestionVo();
                quizQuestionVo.setId(entry.getKey());
                quizQuestionVo.setQuizId(quizId);
                quizQuestionVo.setQuestionContent(entry.getValue().get(0).getQuestionContent());
                List<QuizAnswer> quizAnswerList = new ArrayList<>();
                quizQuestionVo.setQuizAnswerList(quizAnswerList);
                quizAnswerList.addAll(entry.getValue());
                questionVoList.add(quizQuestionVo);
            }

        }
        return quizVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response<String> saveQuizResult(QuizVo quizVo) throws Exception {
        Response<String> response = new Response<>();
        log.info("saveQuizResult request=={}" + JSON.toJSONString(quizVo));
        if(quizVo == null && !CollectionUtils.isEmpty(quizVo.getUserQuizResultVoList())) {
            throw new Exception("传入参数有误");
        }
        // 插入用户回答表
        Long userQuizId = UUIDUtil.nextId();
        quizVo.getUserQuizResultVoList().forEach(v ->{
            v.setUserQuizId(userQuizId);
        });
        List<UserQuizResult> quizResults = new ArrayList<>();
        quizResults.addAll(quizVo.getUserQuizResultVoList());
        if(!CollectionUtils.isEmpty(quizResults)) {
            userQuizResultMapper.insertByList(quizResults);
        }
        // 插入用户回答实验表
        UserQuiz userQuiz = quizVo.getUserQuiz();
        userQuiz.setId(userQuizId);
        userQuiz.setIsCheck(false);
        userQuizMapper.insert(userQuiz);
        response.setData(String.valueOf(userQuizId));
        return response;
    }

    @Override
    public Page<UserResult> findPersonalQuiz(Page page,Long userId) {

        // 测试分数
        List<UserQuiz> userQuizList = userQuizMapper.findByUserId(userId);

        List<Long> quizIdList = userQuizList.stream().map(p -> p.getQuizId()).collect(Collectors.toList());

        List<Quiz> quizList = quizMapper.selectByQuizIds(quizIdList);

        List<Conclusion> conclusionList = conclusionMapper.findByQuizIdAndUserId(quizIdList,userId);

        List<Performance> performanceList = performanceMapper.findByQuizIdAndUserId(quizIdList,userId);

        List<UserResult> userResults = new ArrayList<>();
        userQuizList.stream().forEach(t -> {
            UserResult userResult = new UserResult();
            userResult.setId(UUIDUtil.nextId());
            userResult.setUserId(userId);
            userResult.setQuizId(t.getQuizId());
            Conclusion conclusion = conclusionList.stream().filter(p -> p.getQuizId().equals(t.getQuizId())).findFirst().orElse(new Conclusion());
            Performance performance = performanceList.stream().filter(p -> p.getQuizId().equals(t.getQuizId())).findFirst().orElse(new Performance());

            Quiz quiz = quizList.stream().filter(p -> p.getId().equals(t.getQuizId())).findFirst().orElse(new Quiz());
            userResult.setQuizTitle(quiz.getTitle());

            Integer conclusionScore = conclusion.getScore() != null&& conclusion.getScore() != 0 ? conclusion.getScore() : 0;
            Integer performanceScore = performance.getScore() != null && performance.getScore()!=0 ?performance.getScore(): 0;
            Integer t1 = t.getTotalScore() + conclusionScore + performanceScore;
            userResult.setTotalScore(t1);
            userResults.add(userResult);
        });
        return page.setRecords(userResults);
    }
}
